package org.vehicle.iface;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.vehicle.entity.AlertInfo;
import org.vehicle.entity.OrganizationInfo;
import org.vehicle.service.AlertInfoService;
import org.vehicle.service.OrganizationInfoService;
import org.vehicle.service.redis.RedisService;
import org.vehicle.util.CommonUtil;
import org.vehicle.util.FtpUtil;
import org.vehicle.util.JsonUtils;
import org.vehicle.vo.DeviceAlertVO;

import com.fasterxml.jackson.databind.JsonNode;

@Controller
@RequestMapping("interface/deviceAlert")
public class DeviceAlertController {
	
	private static Logger logger = LogManager.getLogger(DeviceAlertController.class.getName());
	@Autowired
	private AlertInfoService alertInfoService;
	@Autowired
	private RedisService redisService;
	@Autowired
	private OrganizationInfoService organizationInfoService;
	/**
	 * 处理告警
	 * @param deviceAlertVO
	 * @return
	 */
	@RequestMapping("disposeAlert")
	@ResponseBody
	public ResponseEntity<Map<String, Object>> getVehicleInfoAndAlert(HttpServletRequest req,@RequestBody DeviceAlertVO deviceAlertVO){
		Map<String, Object> retMap=new HashMap<String, Object>();
		FTPClient ftpClient=null;
		try{
			String token=req.getParameter("Token");
			String info=redisService.getString(token);
			Long organizationInfoId=JsonUtils.fromJson(info).get("organizationInfoId").asLong();
			OrganizationInfo organizationInfo=organizationInfoService.selectByPrimaryKey(organizationInfoId);
			String managerName=JsonUtils.fromJson(info).get("managerName").asText();
			AlertInfo alertInfo=new AlertInfo();
			alertInfo.setAlertInfoId(Long.parseLong(deviceAlertVO.getAlertInfoId()));
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
			String ftp_photoDirectory="image/" + sdf.format(new Date());
			if(deviceAlertVO.getDisposePicBase64()!=null&&!"".equals(deviceAlertVO.getDisposePicBase64())){
				ftpClient=FtpUtil.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
				byte[] disposePicBytes=Base64Utils.decodeFromString(deviceAlertVO.getDisposePicBase64());
				String disposePicFileName=FtpUtil.generateFileName("disposePic.jpg");
				try(InputStream is=new ByteArrayInputStream(disposePicBytes)){
					FtpUtil.upload(disposePicFileName, is, ftpClient);
					alertInfo.setDisposePic(ftp_photoDirectory+"/"+disposePicFileName);
				}catch (Exception e) {
					logger.error(e);
				}
			}
			alertInfo.setDisposeName(organizationInfo.getOrganizationName()+"_"+managerName);
			alertInfo.setDisposeResult(deviceAlertVO.getDisposeResult());
			alertInfo.setState(2);
			alertInfoService.updateByPrimaryKeySelective(alertInfo);
			retMap.put("state", 1);
			retMap.put("msg", "操作成功");
		}catch(Exception e){
			logger.error(e);
			retMap.put("state", 0);
			retMap.put("msg", "操作失败");
		}finally {
			if(ftpClient!=null){
				try{
					FtpUtil.closeConnection(ftpClient);
				}catch(Exception e){
					ftpClient=null;
				}
			}
		}
		return new ResponseEntity<Map<String,Object>>(retMap, HttpStatus.OK);
	}
	
	/**
	 * 获取省厅人员告警信息
	 * @param devicePersonPageVO
	 * @return
	 */
	@RequestMapping("getPoliceAlertInfo")
	public ResponseEntity<Map<String,Object>> getPoliceAlertInfo(HttpServletRequest req,@RequestBody DeviceAlertVO deviceAlertVO){
		Map<String, Object> retMap=new HashMap<String, Object>();
		try{
			AlertInfo alertInfo=alertInfoService.selectByPrimaryKey(Long.parseLong(deviceAlertVO.getAlertInfoId()));
			if(alertInfo!=null){
				if(alertInfo.getAlertType()!=2){
					retMap.put("state", 0);
					retMap.put("msg", "操作失败");
				}else{
					String alertJson=alertInfo.getAlertComment();
					Iterator<JsonNode> zbryList=JsonUtils.fromJson(alertJson).iterator();
					List<Map<String, Object>> alertList=new ArrayList<Map<String, Object>>();
					if(zbryList.hasNext()){
						while(zbryList.hasNext()){
							JsonNode zbry=zbryList.next();
							Map<String, Object> alertMap=new HashMap<String, Object>();
							alertMap.put("alertTaskName", ObjectUtils.isEmpty(zbry.get("rwmc"))?null:zbry.get("rwmc").asText());
							alertMap.put("alertComment", ObjectUtils.isEmpty(zbry.get("aqms"))?null:zbry.get("aqms").asText());
							alertMap.put("alertLinkName", ObjectUtils.isEmpty(zbry.get("bklxr"))?null:zbry.get("bklxr").asText());
							alertMap.put("alertLinkPhone", ObjectUtils.isEmpty(zbry.get("bklxfs"))?null:zbry.get("bklxfs").asText());
							alertMap.put("alertType", ObjectUtils.isEmpty(zbry.get("rylb"))?null:zbry.get("rylb").asText());
							alertMap.put("alertHandleFun", ObjectUtils.isEmpty(zbry.get("clfs"))?null:zbry.get("clfs").asText());
							alertList.add(alertMap);
						}
					}
					retMap.put("state", 1);
					retMap.put("msg", "操作成功");
					retMap.put("alertList", alertList);
				}
			}else{
				retMap.put("state", 0);
				retMap.put("msg", "操作失败");
			}
		}catch(Exception e){
			logger.error(e);
			retMap.put("state", 0);
			retMap.put("msg", "操作失败");
		}
		return new ResponseEntity<Map<String,Object>>(retMap, HttpStatus.OK);
	}
}
